<template>
    <div class="user-management-container">
      <!-- 用户管理 -->
      <el-card class="user-card" v-loading="usersLoading">
        <template #header>
          <div class="card-header">
            <el-icon><User /></el-icon>
            <span>用户列表</span>
          </div>
        </template>
        
        <!-- 搜索区域 -->
        <div class="user-search-area">
          <el-form :inline="true" :model="userSearchForm" class="search-form">
            <el-form-item label="用户">
              <el-input 
                v-model="userSearchForm.keyword"
                placeholder="输入米米号/邮箱"
                clearable
                @keyup.enter="handleUserSearch"
              />
            </el-form-item>
            
            <el-form-item label="批量查询">
              <el-input
                v-model="bulkQueryInput"
                type="textarea"
                :rows="1"
                placeholder="多个米米号(换行分隔)"
                clearable
                style="width: 220px;"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="handleUserSearch">查询</el-button>
              <el-button @click="handleUserReset">重置</el-button>
            </el-form-item>
          </el-form>
          
          <!-- 批量操作按钮 -->
          <div class="batch-operation-area" v-if="selectedUsers.length > 0">
            <div class="batch-info">
              <el-icon><InfoFilled /></el-icon>
              已选择 <span class="selected-count">{{ selectedUsers.length }}</span> 位用户
            </div>
            <div class="batch-actions">
              <el-button type="danger" @click="openBatchBanDialog">
                <el-icon><Lock /></el-icon> 批量封号
              </el-button>
              <!-- 添加批量解封按钮 -->
              <el-button type="success" @click="openBatchUnbanDialog">
                <el-icon><Unlock /></el-icon> 批量解封
              </el-button>
              <el-button @click="clearSelection">
                <el-icon><Close /></el-icon> 取消选择
              </el-button>
            </div>
          </div>
        </div>
        
        <div class="table-container">
          <!-- 用户表格 - 添加展开行功能 -->
          <el-table 
            ref="userTableRef"
            :data="users" 
            style="width: 100%;" 
            border 
            stripe 
            @selection-change="handleSelectionChange"
            :row-class-name="getUserRowClass"
            :row-key="'account'"  
            @expand-change="handleExpandChange"
          >
            <!-- 添加展开列 -->
            <el-table-column type="expand">
              <template #default="props">
                <div class="expanded-row">
                  <div class="user-detail-panel">
                    <h4>用户物品列表 - {{ props.row.account }}</h4>
                    
                    <!-- 添加物品搜索栏 -->
                    <div class="items-search-bar">
                      <el-form :inline="true" :model="itemSearchForm" class="search-form">
                        <el-form-item label="物品ID">
                          <el-input 
                            v-model="itemSearchForm.itemId"
                            placeholder="输入物品ID"
                            clearable
                            @keyup.enter="searchUserItems"
                          />
                        </el-form-item>
                        
                        <el-form-item label="物品类型">
                          <el-select 
                            v-model="itemSearchForm.itemType" 
                            placeholder="选择物品类型"
                            clearable
                            style="width: 120px;"
                          >
                            <el-option label="全部" :value="undefined" />
                            <el-option label="精灵" :value="1" />
                            <el-option label="道具" :value="2" />
                            <el-option label="时装" :value="3" />
                          </el-select>
                        </el-form-item>
                        
                        <el-form-item>
                          <el-button type="primary" @click="searchUserItems">搜索</el-button>
                          <el-button @click="resetItemSearch">重置</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                    
                    <!-- 物品/宠物嵌套表格 -->
                    <div class="items-table-container">
                      <el-table
                        :data="userItems"
                        border
                        style="width: 100%"
                        size="small"
                        v-loading="itemsLoading"
                      >
                        <el-table-column prop="id" label="ID" min-width="60" />
                        <el-table-column prop="name" label="物品名称" min-width="120" />
                        <el-table-column prop="type" label="物品类型" min-width="90">
                          <template #default="scope">
                            <el-tag :type="getItemTypeTag(scope.row.type)">{{ scope.row.type }}</el-tag>
                          </template>
                        </el-table-column>
                        <el-table-column prop="quantity" label="物品数量" min-width="80" />
                        <el-table-column prop="level" label="等级" min-width="60" />
                        <el-table-column prop="iv" label="个体" min-width="60">
                          <template #default="scope">
                            <span :class="getIvClass(scope.row.iv)">{{ scope.row.iv }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="Shiny" label="异色" min-width="70">
                          <template #default="scope">
                            <el-tag v-if="scope.row.Shiny == 1 || scope.row.Shiny === true" type="warning" effect="dark">异色</el-tag>
                            <span v-else>-</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="nature" label="性格" min-width="80" />
                        <el-table-column prop="ability" label="特性" min-width="100" />
                        <el-table-column prop="addMaxHP" label="额HP" min-width="60" />
                        <el-table-column prop="hp" label="HP" min-width="60" />
                        <el-table-column prop="attack" label="攻击" min-width="60" />
                        <el-table-column prop="defense" label="防御" min-width="60" />
                        <el-table-column prop="spAttack" label="特攻" min-width="60" />
                        <el-table-column prop="spDefense" label="特防" min-width="60" />
                        <el-table-column prop="speed" label="速度" min-width="60" />
                        <el-table-column prop="catchTime" label="捕获时间" min-width="150">
                          <template #default="scope">
                            {{ scope.row.catchTime }}
                          </template>
                        </el-table-column>
                        <el-table-column label="操作" fixed="right" min-width="150">
                          <template #default="scope">
                            <el-button
                              size="small"
                              type="danger"
                              @click="handleItemAction(props.row.account, scope.row, 'delete')"
                            >
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                      
                      <!-- 物品分页 -->
                      <div class="items-pagination" v-if="userItemsTotal > 0">
                        <el-pagination
                          v-model:current-page="itemsCurrentPage"
                          v-model:page-size="itemsPageSize"
                          :page-sizes="[5, 10, 20, 50]"
                          :total="userItemsTotal"
                          layout="total, sizes, prev, pager, next"
                          @size-change="handleItemsSizeChange"
                          @current-change="handleItemsPageChange"
                          background
                          small
                        />
                      </div>
                      
                      <!-- 无数据提示 -->
                      <!-- <el-empty v-if="userItems.length === 0 && !itemsLoading" description="暂无物品数据" /> -->
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            
            <!-- 保留原有的其他列 -->
            <el-table-column 
              type="selection" 
              min-width="55" 
              :reserve-selection="true" 
            />
            <el-table-column prop="id" label="ID" min-width="80" />
            <el-table-column prop="account" label="米米号" min-width="120" />
            <el-table-column prop="email" label="邮箱" min-width="180" />
            <el-table-column prop="role" label="角色" min-width="100">
              <!-- 可能需要格式化角色 -->
            </el-table-column>
            
            <!-- 游戏状态列 - 直接使用中文状态 -->
            <el-table-column label="游戏状态" min-width="110">
              <template #default="scope">
                <!-- 根据 scope.row.gameStatus 的值设置标签类型 -->
                <el-tag :type="scope.row.gameStatus === '正常' ? 'success' : 'danger'" disable-transitions>
                  <!-- 直接显示后端返回的状态 -->
                  {{ scope.row.gameStatus }}
                  <!-- 可选：显示封禁到期时间 -->
                  <span v-if="scope.row.gameStatus === '封号' && scope.row.gameBanEndTime" class="ban-end-time-tag">
                     (至: {{ formatBanEndTime(scope.row.gameBanEndTime) }})
                  </span>
                </el-tag>
              </template>
            </el-table-column>
    
            <!-- 交易状态列 - 直接使用中文状态 -->
            <el-table-column label="交易状态" min-width="110">
              <template #default="scope">
                 <!-- 根据 scope.row.tradeStatus 的值设置标签类型 -->
                <el-tag :type="scope.row.tradeStatus === '正常' ? 'success' : 'danger'" disable-transitions>
                  <!-- 直接显示后端返回的状态 -->
                  {{ scope.row.tradeStatus }}
                   <!-- 可选：显示封禁到期时间 -->
                   <span v-if="scope.row.tradeStatus === '封号' && scope.row.tradeBanEndTime" class="ban-end-time-tag">
                      (至: {{ formatBanEndTime(scope.row.tradeBanEndTime) }})
                   </span>
                </el-tag>
              </template>
            </el-table-column>
    
            <el-table-column prop="createTime" label="注册时间" min-width="180">
              <template #default="scope">
                {{ formatDateFull(scope.row.createTime) }}
              </template>
            </el-table-column>
            
            <!-- 新增封禁时长列 -->
            <el-table-column label="封禁时长" min-width="120">
              <template #default="scope">
                <span v-if="scope.row.gameStatus === '封号' && scope.row.banDuration">
                  {{ scope.row.banDuration === '0' ? '永久' : `${scope.row.banDuration}天` }}
                </span>
                <span v-else-if="scope.row.tradeStatus === '封号' && scope.row.banDuration">
                  {{ scope.row.banDuration === '0' ? '永久' : `${scope.row.banDuration}天` }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            
            <!-- 新增封禁理由列 -->
            <el-table-column label="封禁理由" min-width="150">
              <template #default="scope">
                <el-tooltip 
                  v-if="scope.row.gameStatus === '封号' && scope.row.banReason" 
                  :content="scope.row.banReason" 
                  placement="top" 
                  effect="light">
                  <span class="ban-reason">{{ scope.row.banReason }}</span>
                </el-tooltip>
                <el-tooltip 
                  v-else-if="scope.row.tradeStatus === '封号' && scope.row.banReason" 
                  :content="scope.row.banReason" 
                  placement="top" 
                  effect="light">
                  <span class="ban-reason">{{ scope.row.banReason }}</span>
                </el-tooltip>
                <span v-else>-</span>
              </template>
            </el-table-column>
            
            <!-- 新增管理员封禁理由列 -->
            <el-table-column label="管理员封禁理由" min-width="180">
              <template #default="scope">
                <el-tooltip 
                  v-if="scope.row.gameStatus === '封号' && scope.row.rootReason" 
                  :content="scope.row.rootReason" 
                  placement="top" 
                  effect="light">
                  <span class="admin-reason">{{ scope.row.rootReason }}</span>
                </el-tooltip>
                <el-tooltip 
                  v-else-if="scope.row.tradeStatus === '封号' && scope.row.rootReason" 
                  :content="scope.row.rootReason" 
                  placement="top" 
                  effect="light">
                  <span class="admin-reason">{{ scope.row.rootReason }}</span>
                </el-tooltip>
                <span v-else>-</span>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" min-width="120" fixed="right">
              <template #default="scope">
                <el-button 
                  type="primary" 
                  size="small"
                  @click="viewUserDetail(scope.row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="userCurrentPage"
              v-model:page-size="userPageSize"
              :page-sizes="[10, 20, 50, 1000]"
              :total="userTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleUserSizeChange"
              @current-change="handleUserPageChange"
              background
            />
          </div>
        </div>
      </el-card>
      
      <!-- 批量封号对话框 -->
      <el-dialog
        v-model="batchBanDialogVisible"
        title="批量封号"
        destroy-on-close
        top="5vh"
        class="batch-ban-dialog"
      >
        <div class="batch-ban-content">
          <el-form :model="batchBanForm" label-width="140px">
            <!-- 新增封号类型选择器 -->
            <el-form-item label="封号类型">
              <select
              style="width: auto; height: 32px; border: 1px solid #dcdfe6; border-radius: 4px; padding: 0 8px; background-color: #fff; font-size: 14px; color: #606266; cursor: pointer;" 
              v-model="batchBanForm.banType"
              >
                <option                 
                  v-for="item in banTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></option>
              </select>
            </el-form-item>
            
            <el-form-item label="封禁时长">
              <select
              style="width: auto; height: 32px; border: 1px solid #dcdfe6; border-radius: 4px; padding: 0 8px; background-color: #fff; font-size: 14px; color: #606266; cursor: pointer;" 
              v-model="batchBanForm.banDuration"
              placeholder="请选择"
              >
                <option                 
                  v-for="item in banDurationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></option>
              </select>
            </el-form-item>
            
            <el-form-item label="封禁理由">
              <el-input v-model="batchBanForm.banReason" type="textarea" placeholder="请输入封禁理由" />
            </el-form-item>
            
            <!-- 新增管理员封禁理由 -->
            <el-form-item label="管理员封禁理由">
              <el-input v-model="batchBanForm.rootReason" type="textarea" placeholder="请输入管理员封禁理由（仅管理员可见）" />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="batchBanDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="executeBatchBan" :loading="batchBanloading">确定</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 批量解封对话框 -->
      <el-dialog
        v-model="batchUnbanDialogVisible"
        title="批量解封"
        destroy-on-close
        top="5vh"
        class="batch-unban-dialog"
      >
        <div class="batch-unban-content">
          <el-form :model="batchUnbanForm" label-width="140px">
            <!-- 解封类型选择器 - 使用原生下拉框 -->
            <el-form-item label="解封类型">
              <select
                style="width: auto; height: 32px; border: 1px solid #dcdfe6; border-radius: 4px; padding: 0 8px; background-color: #fff; font-size: 14px; color: #606266; cursor: pointer;" 
                v-model="batchUnbanForm.unbanType"
                placeholder="请选择解封类型"
              >
                <option                 
                  v-for="item in unbanTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></option>
              </select>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="batchUnbanDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="executeBatchUnban">确定</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 添加删除数量输入对话框 -->
      <el-dialog
        v-model="deleteQuantityDialogVisible"
        title="输入删除数量"
        width="30%"
        destroy-on-close
      >
        <el-form :model="deleteForm" label-width="100px">
          <el-form-item label="物品名称">
            <span>{{ currentDeleteItem?.name || '' }}</span>
          </el-form-item>
          <el-form-item label="当前数量">
            <span>{{ currentDeleteItem?.quantity || 0 }}</span>
          </el-form-item>
          <el-form-item label="删除数量" required>
            <el-input-number 
              v-model="deleteForm.quantity" 
              controls-position="right"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteQuantityDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="confirmDeleteWithQuantity">确认删除</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
</template>

<script setup>
  import { ref, reactive, onMounted, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { 
    User, Lock, Unlock, Close, InfoFilled 
  } from '@element-plus/icons-vue'
  import { getUserList, batchBanUsers, batchUnbanUsers, getUserItems, deleteUserItems } from '@/api/user'
  import { formatDateFull } from '@/utils/utils'
  import { findItemNameById } from '@/utils/itemFinder.js'
  import { getSpecialAbility, getNatureName } from '@/utils/trade.js'
  // 用户列表相关变量
  const usersLoading = ref(false)
  const users = ref([])
  const userTotal = ref(0)
  const userCurrentPage = ref(1)
  const userPageSize = ref(10)
  const userSearchForm = ref({
    keyword: '',
    status: ''
  })
  
  // 使用 ref 定义批量查询输入框的数据
  const bulkQueryInput = ref('')
  
  // 批量封号相关变量
  const batchBanloading = ref(false)
  const selectedUsers = ref([])
  const batchBanDialogVisible = ref(false)
  const batchBanForm = ref({
    banDuration: 3, // 默认3天
    banReason: '',
    banType: 1, // 默认选择游戏封号
    rootReason: '' // 管理员封禁理由
  })
  
  // 封禁时长选项
  const banDurationOptions = [
    { label: '3天', value: 3 },
    { label: '7天', value: 7 },
    { label: '30天', value: 30 },
    { label: '3个月', value: 90 },
    { label: '半年', value: 180 },
    { label: '1年', value: 365 },
    { label: '永久', value: 0 }
  ]
  
  // 添加封号类型选项
  const banTypeOptions = [
    { label: '游戏封号', value: 1 },
    { label: '交易封号', value: 2 }
  ]
  
  // 添加批量解封相关变量
  const batchUnbanDialogVisible = ref(false)
  const batchUnbanForm = ref({
    unbanType: 1, // 默认选择游戏解封
    unbanReason: ''
  })
  
  // 解封类型选项
  const unbanTypeOptions = [
    { label: '游戏解封', value: 1 },
    { label: '交易解封', value: 2 }
  ]
  
  // 用户表格引用
  const userTableRef = ref(null)
  
  // 当前展开行的用户账号
  const currentExpandedAccount = ref(null)
  
  // 用户物品相关变量
  const userItems = ref([])
  const userItemsTotal = ref(0)
  const itemsCurrentPage = ref(1)
  const itemsPageSize = ref(10)
  const itemsLoading = ref(false)
  
  // 添加物品搜索表单
  const itemSearchForm = ref({
    itemId: '',
    itemType: undefined
  })
  
  // 添加删除数量对话框相关变量
  const deleteQuantityDialogVisible = ref(false)
  const currentDeleteItem = ref(null)
  const currentDeleteAccount = ref('')
  const deleteForm = reactive({
    quantity: 1
  })
  
  // 获取用户列表数据
  const fetchUsers = async () => {
    try {
      usersLoading.value = true
      
      // 准备 API 请求参数
      const params = {
        currentPage: userCurrentPage.value,
        limit: userPageSize.value,
        keyword: userSearchForm.value.keyword == '' ? undefined: userSearchForm.value.keyword,
        status: userSearchForm.value.status !== '' ? parseInt(userSearchForm.value.status) : undefined
      }
      
      // 处理批量查询输入
      if (bulkQueryInput.value.trim()) {
        // 解析批量输入的内容，按逗号、空格、换行符分割
        const bulkAccounts = bulkQueryInput.value
          .split(/[\s,;\n]+/) // 使用正则表达式匹配多种分隔符
          .map(item => item.trim()) // 去除每个条目两端的空格
          .filter(item => item !== ''); // 过滤掉空条目
        
        // 将批量用户列表添加到请求参数中
        if (bulkAccounts.length > 0) {
          params.bulkAccounts = bulkAccounts;
        }
      }
      
      // 调用 API 获取用户列表
      const response = await getUserList(params)
      
      if (response.code === 200) {
        // 为每个用户添加 Switch 所需的属性
        users.value = response.data.list.map(user => ({
          ...user,
        }))
        userTotal.value = response.data.totalCount
        userCurrentPage.value = response.data.currentPage
        userPageSize.value = response.data.pageSize
      } else {
        ElMessage.error(response.msg || '获取用户列表失败')
      }
    } catch (error) {
      console.error('获取用户列表出错:', error)
      ElMessage.error('获取用户列表失败')
    } finally {
      usersLoading.value = false
    }
  }
  
  // 用户表格操作的处理函数
  const handleUserSearch = () => {
    userCurrentPage.value = 1
    fetchUsers()
  }
  
  // 重置函数，清空查询条件和批量查询输入框
  const handleUserReset = () => {
    userSearchForm.value.keyword = ''
    userSearchForm.value.status = ''
    bulkQueryInput.value = '' // 清空批量查询输入
    userCurrentPage.value = 1
    fetchUsers()
  }
  
  // 分页处理函数
  const handleUserPageChange = (page) => {
    userCurrentPage.value = page
    fetchUsers()
  }
  
  const handleUserSizeChange = (size) => {
    userPageSize.value = size
    userCurrentPage.value = 1
    fetchUsers()
  }
  
  // 处理表格多选变化
  const handleSelectionChange = (selection) => {
    selectedUsers.value = selection 
    console.log(selectedUsers.value)
  }
  
  // 清空所有选择
  const clearSelection = () => {
    selectedUsers.value = []
    if (userTableRef.value) {
      userTableRef.value.clearSelection()
    }
  }
  
  // 打开批量封号对话框
  const openBatchBanDialog = () => {
    if (selectedUsers.value.length === 0) {
      ElMessage.warning('请先选择要封禁的用户')
      return
    }
    
    batchBanDialogVisible.value = true
  }
  
  // 执行批量封号操作
  const executeBatchBan = async () => {
    if (selectedUsers.value.length === 0) {
      ElMessage.warning('请先选择要封禁的用户')
      return
    }
    
    const accounts = selectedUsers.value.map(user => user.account)
    const { banDuration, banReason, banType, rootReason } = batchBanForm.value
    
    // 确认对话框
    const banDurationText = banDurationOptions.find(option => option.value === banDuration)?.label || `${banDuration}天`
    const banTypeText = banTypeOptions.find(option => option.value === banType)?.label || '普通封号'
    
    ElMessageBox.confirm(
      `您确定要对已选择的 ${accounts.length} 名用户执行${banTypeText}，时长${banDurationText}吗？`,
      '批量封号确认',
      {
        confirmButtonText: '确定封号',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
    )
      .then(async () => {
        batchBanloading.value = true
        try {
          const result = await batchBanUsers({
            accounts,
            banDuration,
            banReason,
            rootReason: batchBanForm.value.rootReason,
            banType
          })
          
          if (result.code === 200) {
            ElMessage.success(`成功对 ${accounts.length} 名用户执行${banTypeText}`)
            batchBanDialogVisible.value = false
            
            // 重新加载用户列表
            fetchUsers()
            
            // 清空选择
            clearSelection()
  
            // 清空表单
            batchBanForm.value = { banDuration: 3, banReason: '', rootReason: '', banType: 1 }
          } else {
            ElMessage.error(result.msg || '批量封号失败')
          }
        } catch (error) {
          console.error('批量封号失败:', error)
          ElMessage.error('批量封号操作失败')
        } finally {
          batchBanloading.value = false
        }
      })
      .catch(() => {
        ElMessage.info('已取消批量封号操作')
      })
  }
  
  // 打开批量解封对话框
  const openBatchUnbanDialog = () => {
    if (selectedUsers.value.length === 0) {
      ElMessage.warning('请先选择要解封的用户')
      return
    }
    
    batchUnbanDialogVisible.value = true
  }
  
  // 执行批量解封操作
  const executeBatchUnban = async () => {
    if (selectedUsers.value.length === 0) {
      ElMessage.warning('请先选择要解封的用户')
      return
    }
    
    const accounts = selectedUsers.value.map(user => user.account)
    const { unbanType, unbanReason } = batchUnbanForm.value
    
    // 确认对话框
    const unbanTypeText = unbanTypeOptions.find(option => option.value === unbanType)?.label || '游戏解封'
    
    ElMessageBox.confirm(
      `您确定要对已选择的 ${accounts.length} 名用户执行${unbanTypeText}吗？`,
      '批量解封确认',
      {
        confirmButtonText: '确定解封',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
    )
      .then(async () => {
        try {
          // 调用API执行批量解封
          const result = await batchUnbanUsers({
            accounts,
            unbanType
          })
          
          if (result.code === 200) {
            ElMessage.success(`成功对 ${accounts.length} 名用户执行${unbanTypeText}`)
            batchUnbanDialogVisible.value = false
            
            // 重新加载用户列表
            fetchUsers()
            
            // 清空选择
            clearSelection()
          } else {
            ElMessage.error(result.msg || '批量解封失败')
          }
        } catch (error) {
          console.error('批量解封失败:', error)
          ElMessage.error('批量解封操作失败')
        }
      })
      .catch(() => {
        ElMessage.info('已取消批量解封操作')
      })
  }
  
  // 获取用户行的样式类
  const getUserRowClass = ({ row }) => {
    return row.status === 0 ? 'banned-row' : ''
  }
  
  // 格式化封禁结束时间
  const formatBanEndTime = (endTime) => {
    if (!endTime) return ''
    
    const now = new Date()
    const end = new Date(endTime)
    
    if (end <= now) return '已过期'
    
    const diffDays = Math.ceil((end - now) / (1000 * 60 * 60 * 24))
    return `还剩 ${diffDays} 天`
  }
  
  // 查看用户详情
  const viewUserDetail = (user) => {
    ElMessage.info('用户详情功能开发中')
    console.log('查看用户详情:', user)
  }
  
  // 处理展开行事件
  const handleExpandChange = (row, expandedRows) => {
    if (expandedRows.length > 0) {
      const account = row.account
      currentExpandedAccount.value = account
      console.log('展开行，用户账号:', account)
      // 加载该用户的物品信息
      loadUserItems(account)
    } else {
      currentExpandedAccount.value = null
      // 清空物品列表
      userItems.value = []
    }
  }
  
  // 加载用户物品信息
  const loadUserItems = async (account) => {
    if (!account) return
    
    itemsLoading.value = true
    userItems.value = [] // 清空现有数据
    
    try {
      console.log(`加载用户 ${account} 的物品数据，页码: ${itemsCurrentPage.value}, 每页: ${itemsPageSize.value}`)
      
      // 调用API获取用户物品列表
      const response = await getUserItems({
        currentPage: itemsCurrentPage.value,
        limit: itemsPageSize.value,
        account: Number(account), // 确保account是数字类型
        itemId: itemSearchForm.value.itemId ? Number(itemSearchForm.value.itemId) : undefined, // 添加物品ID搜索
        itemType: itemSearchForm.value.itemType // 添加物品类型筛选
      })
      
      if (response.code === 200) {
        // 处理接口返回的数据
        const processedData = response.data.list.map(item => {
          // 处理不同类型物品的数据格式
          let processedItem = {
            id: item.uuid || `${item.userid}-${item.itemId}`,
            itemId: item.itemId,
            uuid: item.uuid,
            name: findItemNameById(item.itemId, item.itemType), // 传入itemId和物品类型
            type: getItemTypeName(item.itemType), // 转换物品类型
            quantity: item.quantity,
            level: item.level || '-',
            iv: item.iv || '-',
            nature: getNatureName(item.nature), // 需要将数字转为性格名称
            ability: getSpecialAbility(item.special), // 需要根据特性ID获取名称
            addMaxHP: item.addMaxHP || '-',
            hp: item.hp || '-',
            attack: item.EVAttack || '-',
            defense: item.EVDefence || '-',
            spAttack: item.EVSA || '-',
            spDefense: item.EVSD || '-',
            speed: item.EVSP || '-',
            Shiny: item.shiny,
            catchTime: item.catchTime
          }
          return processedItem;
        });
        
        userItems.value = processedData
        userItemsTotal.value = response.data.totalCount
        itemsCurrentPage.value = response.data.currentPage
        itemsPageSize.value = response.data.pageSize
      } else {
        ElMessage.error(response.msg || '获取物品列表失败')
      }
    } catch (error) {
      console.error('加载用户物品错误:', error)
      ElMessage.error('加载用户物品失败')
    } finally {
      itemsLoading.value = false
    }
  }
  
  // 根据物品类型获取类型名称
  const getItemTypeName = (typeId) => {
    switch (Number(typeId)) {
      case 1: return '精灵'
      case 2: return '道具'
      case 3: return '时装'
      default: return '未知'
    }
  }
  
  // 处理物品分页变化
  const handleItemsPageChange = (page) => {
    itemsCurrentPage.value = page
    if (currentExpandedAccount.value) {
      loadUserItems(currentExpandedAccount.value)
    }
  }
  
  const handleItemsSizeChange = (size) => {
    itemsPageSize.value = size
    itemsCurrentPage.value = 1
    if (currentExpandedAccount.value) {
      loadUserItems(currentExpandedAccount.value)
    }
  }
  
  // 搜索用户物品
  const searchUserItems = () => {
    itemsCurrentPage.value = 1
    if (currentExpandedAccount.value) {
      loadUserItems(currentExpandedAccount.value)
    }
  }
  
  // 重置物品搜索
  const resetItemSearch = () => {
    itemSearchForm.value.itemId = ''
    itemSearchForm.value.itemType = undefined
    itemsCurrentPage.value = 1
    if (currentExpandedAccount.value) {
      loadUserItems(currentExpandedAccount.value)
    }
  }
  
  // 处理物品操作
  const handleItemAction = (account, item, action) => {
    console.log(`处理用户 ${account} 的物品操作:`, item, action)
    
    switch (action) {
      case 'view':
        ElMessage.info(`查看物品详情: ${item.id}`)
        // 实现查看物品详情的逻辑
        break
      case 'delete':
        // 保存当前操作的物品对象
        currentDeleteItem.value = item
        currentDeleteAccount.value = account
        
        // 根据物品类型区分删除逻辑
        if (item.type === "精灵") {
          // 精灵类型：直接确认删除
          ElMessageBox.confirm(
            `确定要删除精灵 ${item.name || '未知'} 吗？此操作不可恢复。`,
            '删除确认',
            {
              confirmButtonText: '确定删除',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              deleteItem(account, item.itemId, 1)
            })
            .catch(() => {
              ElMessage.info('已取消删除')
            })
        } else {
          // 道具或时装类型：需要输入删除数量
          deleteForm.quantity = 1  // 默认值
          if (item.quantity) {
            // 设置最大允许删除数量
            deleteForm.quantity = Math.min(deleteForm.quantity, item.quantity)
          }
          deleteQuantityDialogVisible.value = true
        }
        break
    }
  }
  
  // 添加确认删除数量的方法
  const confirmDeleteWithQuantity = () => {
    if (!currentDeleteItem.value || !currentDeleteAccount.value) {
      ElMessage.error('删除信息不完整')
      return
    }
    
    const item = currentDeleteItem.value
    const account = currentDeleteAccount.value
    const quantity = deleteForm.quantity
    
    // 验证数量
    // 特殊物品ID 999888 不需要检查数量限制
    if (item.itemId !== 999888) {
      if (quantity <= 0 || quantity > item.quantity) {
        ElMessage.error('删除数量无效')
        return
      }
    }
    
    // 关闭对话框
    deleteQuantityDialogVisible.value = false
    
    // 执行删除
    deleteItem(account, item.itemId, quantity)
  }
  
  // 统一的删除物品逻辑
  const deleteItem = async (account, itemId, quantity) => {
    try {
      // 获取当前操作的物品信息
      const item = currentDeleteItem.value;
      
      // 判断物品类型，获取正确的itemType和catchTime
      let itemType, catchTime;
      
      if (item) {
        // 将类型名称转换为类型ID
        itemType = getItemTypeId(item.type);
        // 如果是精灵，获取捕获时间；否则为0
        catchTime = itemType === 1 ? (item.catchTime || 0) : 0;
      } else {
        // 如果没有currentDeleteItem，使用默认值
        itemType = 2; // 默认为道具
        catchTime = 0;
      }
      
      // 调用删除API
      const response = await deleteUserItems({
        account: Number(account),
        itemId: Number(itemId),
        itemType: itemType,
        sellNum: quantity,
        catchTime: catchTime
      });
      
      if (response.code === 200) {
        ElMessage.success(`已成功删除${quantity}个物品`);
        // 重新加载物品列表
        loadUserItems(account);
      } else {
        ElMessage.error(response.msg || '删除物品失败');
      }
    } catch (error) {
      console.error('删除物品时出错:', error);
      ElMessage.error('删除物品失败，请重试');
    }
  }
  
  // 添加物品类型名称转ID的函数
  const getItemTypeId = (typeName) => {
    switch (typeName) {
      case '精灵': return 1;
      case '道具': return 2;
      case '时装': return 3;
      default: return 2; // 默认为道具
    }
  }
  
  // 获取物品类型标签样式
  const getItemTypeTag = (type) => {
    switch (type) {
      case '精灵': return 'primary'
      case '道具': return 'success'
      case '时装': return 'warning'
      default: return 'info'
    }
  }
  
  // 获取个体值样式
  const getIvClass = (iv) => {
    if (iv === '-') return ''
    const ivNum = Number(iv)
    if (ivNum >= 90) return 'iv-excellent'
    if (ivNum >= 75) return 'iv-good'
    if (ivNum >= 60) return 'iv-normal'
    return 'iv-poor'
  }
  
  // 处理用户操作
  const handleUserAction = (account, action) => {
    console.log(`用户 ${account} 的操作: ${action}`)
    
    switch (action) {
      case 'edit':
        ElMessage.info(`编辑用户 ${account} 的信息`)
        // 执行编辑用户的逻辑
        break
      case 'reset-password':
        ElMessage.info(`重置用户 ${account} 的密码`)
        // 执行重置密码的逻辑
        break
      case 'ban-game':
        ElMessage.info(`封禁用户 ${account} 的游戏功能`)
        // 执行封禁游戏的逻辑
        break
      case 'unban-game':
        ElMessage.info(`解封用户 ${account} 的游戏功能`)
        // 执行解封游戏的逻辑
        break
      case 'ban-trade':
        ElMessage.info(`封禁用户 ${account} 的交易功能`)
        // 执行封禁交易的逻辑
        break
      case 'unban-trade':
        ElMessage.info(`解封用户 ${account} 的交易功能`)
        // 执行解封交易的逻辑
        break
    }
  }
  
  // 修复格式化捕获时间的方法
  const formatCatchTime = (timestamp) => {
    if (!timestamp || timestamp === '-') return '-'
    
    try {
      // 确保时间戳是数字
      const ts = Number(timestamp)
      if (isNaN(ts)) return '-'
      
      // 创建日期对象
      const date = new Date(ts * 1000)
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) return '-'
      
      // 格式化日期
      return (
        date.getFullYear() + '-' + 
        String(date.getMonth() + 1).padStart(2, '0') + '-' + 
        String(date.getDate()).padStart(2, '0') + ' ' + 
        String(date.getHours()).padStart(2, '0') + ':' + 
        String(date.getMinutes()).padStart(2, '0') + ':' + 
        String(date.getSeconds()).padStart(2, '0')
      )
    } catch (error) {
      console.error('格式化时间错误:', error)
      return '-'
    }
  }
  
  // 组件挂载时加载用户列表
  onMounted(() => {
    fetchUsers()
  })
</script>

<style lang="scss" scoped>
  .user-management-container {
    padding: 20px;
  }
  
  .user-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    align-items: center;
    
    .el-icon {
      margin-right: 8px;
    }
  }
  
  .user-search-area {
    margin-bottom: 16px;
  }
  
  .search-form {
    margin-bottom: 16px;
  }
  
  /* 批量操作区域样式 */
  .batch-operation-area {
    margin-bottom: 15px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    border-left: 4px solid #409eff;
  }
  
  .batch-info {
    margin-bottom: 5px;
    font-size: 14px;
    color: #606266;
  }
  
  .selected-count {
    font-weight: bold;
    color: #f56c6c;
    margin: 0 3px;
  }
  
  .batch-actions {
    margin-top: 10px;
    margin-bottom: 10px;
    display: flex;
    justify-content: flex-start;
  }
  
  .batch-ban-dialog .el-form,
  .batch-unban-dialog .el-form {
    max-width: 500px;
    margin: 0 auto;
  }
  
  .batch-ban-dialog .el-select,
  .batch-unban-dialog .el-select {
    width: 100%;
  }
  
  .batch-ban-dialog .el-textarea {
    width: 100%;
  }
  
  /* 用户列表中当前禁用状态的行突出显示 */
  :deep(.banned-row) {
    background-color: #fef0f0;
  }
  
  .ban-end-time-tag {
    margin-left: 8px;
    font-size: 12px;
    color: #f56c6c;
    font-style: italic;
  }
  
  /* 分页容器 */
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }

  
  /* 封禁理由和管理员理由列样式 */
  .ban-reason, .admin-reason {
    display: inline-block;
    max-width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    cursor: pointer;
  }
  
  .ban-reason {
    color: #f56c6c;
  }
  
  .admin-reason {
    color: #e6a23c;
  }
  
  // 添加展开行的样式
  .expanded-row {
    padding: 16px;
    
    .user-detail-panel {
      background-color: #f9fafc;
      border-radius: 4px;
      padding: 16px;
      box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.05);
      
      h4 {
        margin-top: 0;
        margin-bottom: 16px;
        color: #409EFF;
        font-weight: 600;
        border-bottom: 1px solid #ebeef5;
        padding-bottom: 8px;
      }
      
      // 添加物品搜索栏样式
      .items-search-bar {
        margin-bottom: 16px;
        padding: 12px;
        background-color: #f0f7ff;
        border-radius: 4px;
        
        .el-form-item {
          margin-bottom: 0;
          margin-right: 12px;
        }
      }
      
      .detail-section {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 12px;
        margin-bottom: 16px;
        
        .detail-item {
          display: flex;
          align-items: center;
          
          .detail-label {
            font-weight: 500;
            color: #606266;
            width: 80px;
            flex-shrink: 0;
          }
          
          .detail-value {
            color: #303133;
          }
        }
      }
      
      .action-section {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        margin-top: 16px;
        padding-top: 16px;
        border-top: 1px solid #ebeef5;
        margin-bottom: 20px;
      }
      
      .items-table-container {
        margin-top: 24px;
        
        h4 {
          margin-bottom: 12px;
        }
      }
      
      .items-pagination {
        margin-top: 16px;
        display: flex;
        justify-content: flex-end;
      }
    }
  }
  
  // 个体值样式
  .iv-excellent {
    color: #67c23a;
    font-weight: bold;
  }
  
  .iv-good {
    color: #409EFF;
  }
  
  .iv-normal {
    color: #e6a23c;
  }
  
  .iv-poor {
    color: #f56c6c;
  }
</style>